package com.explment.lens.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.explment.lens.entity.SysUserEntity;
import com.explment.lens.entity.SysUserPasswordRecordEntity;
import com.explment.lens.mapper.SysUserMapper;
import com.explment.lens.service.SysUserPasswordRecordService;
import com.explment.lens.service.SysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.explment.lens.utils.uuid.UUIDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * 系统用户 service实现类
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUserEntity> implements SysUserService {

    @Autowired
    private SysUserMapper sysUserEntityMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private SysUserPasswordRecordService sysUserPasswordRecordService;

    @Override
    @Transactional
    public boolean save(SysUserEntity entity) {
        SysUserPasswordRecordEntity sysUserPasswordRecordEntity = new SysUserPasswordRecordEntity();
        String password = entity.getPassword();
        if(entity.getAccount() != null){
            SysUserEntity user = sysUserEntityMapper.selectOne(new QueryWrapper<SysUserEntity>().eq("account", entity.getAccount()));
            if(null== user){
                if (password != null) {

                    entity.setPassword(passwordEncoder.encode(password));
                }else {
                    throw new RuntimeException("密码不能为空");
                }
            }else{
                throw new RuntimeException("账号已存在");
            }
        }else {
           throw new RuntimeException("账号不能为空");
        }
        entity.setId(UUIDUtils.fastSimpleUUID());
        int n = sysUserEntityMapper.insert(entity);

        sysUserPasswordRecordEntity.setId(UUIDUtils.fastSimpleUUID());
        sysUserPasswordRecordEntity.setUserId(entity.getId());
        sysUserPasswordRecordEntity.setHistoryPassword(password);
        sysUserPasswordRecordEntity.setUpdatePasswordTime(LocalDateTime.now());
        sysUserPasswordRecordEntity.setUpdateUser(entity.getRealName());
        sysUserPasswordRecordEntity.setCreateUser(entity.getRealName());
        sysUserPasswordRecordEntity.setCreateTime(LocalDateTime.now());
        sysUserPasswordRecordEntity.setUpdateTime(LocalDateTime.now());
        sysUserPasswordRecordService.save(sysUserPasswordRecordEntity);
        return  n > 0 ;
    }
}